﻿using UnityModule;
using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using UnityEngine.Networking;
using UnityEngine;
public class SettingComponent : SingletonBehaviour<SettingComponent>
{
    public class ClientSetting
    {
        public bool ForceUpdate;
        public byte HighTaskMaxCount;
        public byte HighDownLoadTaskMax;
        public byte LowTaskMaxCount;
        public byte LowDownLoadTaskMax;
        public byte DownLoadClinetType;
        public int LimitSpeedK;//单位K
        public int RetryMaxCount;//单个下载任务最大重试次数
        public bool BreakPointResume;//断点续传
        public int RequestTimeouts;//请求超时（秒）
        public bool MonitorEnable;

        public void SetDefault() {
            HighTaskMaxCount = 4;
            HighDownLoadTaskMax = 1;
            LowTaskMaxCount = 2;
            LowDownLoadTaskMax = 2;
            //DownLoadClinetType = (byte)DownloadTask.RequestMode.WebClient;
            ForceUpdate = false;
            RequestTimeouts = 100;
            LimitSpeedK = 2048;
            RetryMaxCount = 5;
            MonitorEnable = false;
        }
    }

    public static IEnumerator LoadClientArg(string url, Action<ClientSetting> onSuccess, Action<string> onFailed) {
        using (UnityWebRequest wwwGetInfo = UnityWebRequest.Get(url))
        {
            wwwGetInfo.timeout = 3;
            DownloadMonitor.Watch((int)DownloadMonitor.ReportId.DownloadClientArgs);
            yield return wwwGetInfo.SendWebRequest();
            if (string.IsNullOrEmpty(wwwGetInfo.error))
            {
                string json = wwwGetInfo.downloadHandler.text;
                Debug.Log("client setting:"+json);


                try
                {
                    ClientSetting cs = JsonUtility.FromJson<ClientSetting>(json);
                    DownloadMonitor.AutoReport((int)DownloadMonitor.ReportId.DownloadClientArgs);
                    onSuccess?.Invoke(cs);         
                    
                }
                catch(Exception e) {
                    onFailed?.Invoke(e.ToString());
                }
            }
            else
            {
                onFailed?.Invoke(wwwGetInfo.error);
            }
            DownloadMonitor.Abort((int)DownloadMonitor.ReportId.DownloadClientArgs);
        }
    }

}

